package com.bor.gb.admin.ui;

import com.bor.gb.db.domain.Place;
import com.bor.gb.db.repositories.PlaceRepository;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import ru.xpoft.vaadin.VaadinView;

@Component
@Scope("prototype")
@VaadinView(PlaceView.NAME)
public class PlaceView extends VerticalLayout implements View {

    public static final String NAME = "PlaceView";

    @Autowired
    private transient PlaceRepository placeRepository;

    @Override
    public void enter(ViewChangeListener.ViewChangeEvent event) {
        HorizontalLayout horizontalLayout = new HorizontalLayout();
        horizontalLayout.setSpacing(true);

        VerticalLayout verticalLayout = new VerticalLayout();

        horizontalLayout.addComponent(verticalLayout);

        // list places
        for (Place place : placeRepository.findAll()) {
            verticalLayout.addComponent(new Label(place.getName()));
        }

        // add new place
        final TextField textField = new TextField();
        horizontalLayout.addComponent(textField);

        Button savePlace = new Button();

        savePlace.setCaption("Save");


        horizontalLayout.addComponent(savePlace);
        savePlace.addClickListener(event1 -> {
            Place place = new Place();
            place.setTown(textField.getValue());
            placeRepository.save(place);
        });


        addComponent(horizontalLayout);
    }
}
